package com.ayoka.parenting.ui.mine;

import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.ayoka.parenting.Constants;
import com.ayoka.parenting.R;
import com.ayoka.parenting.adapter.GrownPathAdapter;
import com.ayoka.parenting.bean.BasicUserInfoBean;
import com.ayoka.parenting.bean.GrownPathBean;
import com.ayoka.parenting.bean.PagerBean;
import com.ayoka.parenting.bean.UserInfoDetailBean;
import com.ayoka.parenting.bean.UserManager;
import com.ayoka.parenting.databinding.FragmentBaseRecyclerviewBinding;
import com.ayoka.parenting.databinding.HeaderMineInfoBinding;
import com.ayoka.parenting.mvp.MVPBaseRecyclerViewFragment;
import com.ayoka.parenting.ui.coach.applycoachcondition.ApplyCoachConditionActivity;
import com.ayoka.parenting.ui.coach.commentstudent.CommentStudentActivity;
import com.ayoka.parenting.ui.coach.studentmanager.StudentManagerActivity;
import com.ayoka.parenting.ui.payment.openmember.OpenMemberActivity;
import com.jincp.common.brvah.BaseQuickAdapter;
import com.jincp.common.brvah.BaseViewHolder;
import com.jincp.common.brvah.item_decoration.TimeLineDecoration;
import com.jincp.common.dialog.DialogHelper;
import com.jincp.common.utils.DateUtil;
import com.jincp.common.utils.StringUtil;
import com.jincp.common.utils.TDevice;
import com.jincp.common.utils.UIUtils;
import com.jincp.filepicker.Constant;
import com.jincp.image.load.ImageLoader;
import com.jincp.image.load.ImageLoaderOptions;

import java.util.Date;

/**
 * @ProjectName: MVPPlugin.
 * @ClassName: MineFragment.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/10/10 18:17.
 */
public class MineFragment extends MVPBaseRecyclerViewFragment<GrownPathBean, FragmentBaseRecyclerviewBinding, MineContract.View, MinePresenter> implements MineContract.View {

    private HeaderMineInfoBinding headerBinding;

    private TimeLineDecoration timeLineDecoration;

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        headerBinding = DataBindingUtil.inflate(LayoutInflater.from(getActivity()), R.layout.header_mine_info, null, false);
        headerBinding.tvCoachHandbook.setOnClickListener(this);
        headerBinding.tvStudentManager.setOnClickListener(this);
        headerBinding.tvBuy.setOnClickListener(this);
        headerBinding.tvApplyCoach.setOnClickListener(this);
        headerBinding.btnRelease.setOnClickListener(this);
        adapter.addHeaderView(headerBinding.getRoot());
    }

    @Override
    protected SwipeRefreshLayout getRefreshLayout() {
        return mDataBinding.swipeRefresh;
    }

    @Override
    protected RecyclerView getRecyclerView() {
        return mDataBinding.recyclerView;
    }

    @NonNull
    @Override
    protected BaseQuickAdapter<GrownPathBean, BaseViewHolder> getAdapter() {
        GrownPathAdapter adapter = new GrownPathAdapter();
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GrownPathBean grownPathBean = (GrownPathBean) adapter.getItem(position);
                CommentStudentActivity.start(getActivity(),grownPathBean.ID);
            }
        });
        return adapter;
    }

    @Override
    protected RecyclerView.ItemDecoration getRecycleDivider() {
        return new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view);
                int count = parent.getAdapter().getItemCount();
                if (position > 0 && position < count - 1) {
                    outRect.right = UIUtils.dp2px(15);
                }
            }
        };
    }

    @Override
    protected void getData(boolean isShowWaitDialog) {
        if (mPresenter != null) {
            mPresenter.getUserInformation();
            mPresenter.getGrownPathListData(isShowWaitDialog, pageNo, pageSize);
        }
    }

    @Override
    protected void initData() {
        getData(true);
    }

    @Override
    protected MinePresenter getPresenter() {
        return new MinePresenter();
    }

    @Override
    public void onClick(View view) {
        if (view == headerBinding.tvCoachHandbook){
            if (mPresenter != null) {
                mPresenter.showNotificationDialog(getChildFragmentManager());
                headerBinding.tvCoachHandbook.setEnabled(false);
            }
        } else if (view == headerBinding.tvStudentManager){
            StudentManagerActivity.start(getActivity());
        } else if (view == headerBinding.tvBuy){
            OpenMemberActivity.start(getActivity());
        } else if (view == headerBinding.tvApplyCoach){
            ApplyCoachConditionActivity.start(getActivity());
        } else if (view == headerBinding.btnRelease){

        }
    }

    @Override
    public void onGetUserInformationCallback(boolean isSuccess) {
        if (UserManager.getInstance().detailBean != null) {
            UserInfoDetailBean detailBean = UserManager.getInstance().detailBean;
            if (detailBean.user_info != null) {
                if (detailBean.user_info.BasicInfo != null) {
                    BasicUserInfoBean basicUserInfoBean = detailBean.user_info.BasicInfo;
                    ImageLoader.getInstance().displayImage(basicUserInfoBean.LocalAvatar, headerBinding.ivUserHeader, ImageLoaderOptions.getCircleOptions(0, 4, Color.WHITE));
                    headerBinding.tvUserName.setText(basicUserInfoBean.WeixinNickName);
                }
                // 设置类型
                if (detailBean.user_info.IsCoach == 0) {
                    headerBinding.tvMemberType.setText(UserManager.getMemberType(detailBean.user_info.IsMembership));
                } else {
                    headerBinding.tvMemberType.setText(UserManager.getCoachType(detailBean.user_info.IsCoach));
                }
                // 设置按钮
                if (detailBean.user_info.IsCoach != 0) {
                    headerBinding.tvCoachHandbook.setVisibility(View.VISIBLE);
                    headerBinding.tvStudentManager.setVisibility(View.VISIBLE);
                } else {
                    if (detailBean.user_info.IsMembership != 2) {
                        headerBinding.tvLeftDays.setVisibility(View.VISIBLE);
                        headerBinding.tvLeftDays.setText(StringUtil.formatString(R.string.format_temp_left_days, formatMemberDay(detailBean.user_info.MembershipExpireDate)));
                        headerBinding.tvBuy.setVisibility(View.VISIBLE);
                    } else {
                        headerBinding.tvLeftDays.setVisibility(View.VISIBLE);
                        headerBinding.tvLeftDays.setText(StringUtil.formatString(R.string.format_member_left_days, formatMemberDay(detailBean.user_info.MembershipExpireDate)));
                        headerBinding.tvApplyCoach.setVisibility(View.VISIBLE);
                    }
                }
                // 设置冥想数据
                int totalMeditation = Math.round(detailBean.user_info.MeditationTotalTime / 60);
                 headerBinding.tvTotalMeditation.setText(String.valueOf(totalMeditation));
                int todayMeditation = Math.round(detailBean.user_info.MeditationTodayTime / 60);
                headerBinding.tvTodayMeditation.setText(String.valueOf(todayMeditation));
                headerBinding.tvTotalMeditationDay.setText(String.valueOf(detailBean.user_info.MeditationTotalDays));
            }
            if (detailBean.has_coach == 1 && detailBean.coach_info != null && detailBean.coach_info.CoachInfo != null && detailBean.coach_info.CoachInfo.BasicInfo != null) {
                BasicUserInfoBean coachInfoBean = detailBean.coach_info.CoachInfo.BasicInfo;
                headerBinding.cardMyCoach.setVisibility(View.VISIBLE);
                ImageLoader.getInstance().displayImage(coachInfoBean.LocalAvatar, headerBinding.ivCoachHeader, ImageLoaderOptions.getCircleOptions());
                headerBinding.tvCoachName.setText(coachInfoBean.WeixinNickName);
                headerBinding.tvCoachType.setText(UserManager.getCoachType(1));
            }
        }
    }

    @Override
    public void configGrownPathListData(PagerBean<GrownPathBean> data) {
        if (data == null) return;
        setLoadMoreLayout(data.list, data.totalPage);
        if (timeLineDecoration == null) {
            timeLineDecoration = new TimeLineDecoration(getActivity(), 0, 1, 0);
            timeLineDecoration.setCircleSize(10);
            timeLineDecoration.setOffsetX(50);
            mDataBinding.recyclerView.addItemDecoration(timeLineDecoration);
        }
    }

    @Override
    public void onDialogDismiss(DialogFragment dialog) {
        headerBinding.tvCoachHandbook.setEnabled(true);
    }

    @Override
    public void openCoachHandBook() {
        TDevice.openBrowser(getActivity(), Constants.COACH_HAND_BOOK);
    }

    private int formatMemberDay(String membershipExpireDate) {
        if (TextUtils.isEmpty(membershipExpireDate)) return 0;
        Date expireDate = DateUtil.parseDate(membershipExpireDate);
        if (expireDate == null) return 0;
        long expireMilliseconds = expireDate.getTime();
        long currentMilliseconds = System.currentTimeMillis();
        long diff = expireMilliseconds - currentMilliseconds;
        if (diff <= 0) return 0;
        int day = (int) Math.floor(diff / (24 * 60 * 60 * 1000));
        return day;
    }
}
